<?php


namespace app\common\models;


use app\common\caches\DummyCache;
use app\common\traits\BaseModelOptionTrait;
use think\Model;
use function GuzzleHttp\json_decode;
use function GuzzleHttp\json_encode;

class Dummy extends Model
{
    use BaseModelOptionTrait;

    protected $table = 'xiangji_dummies';
    // 自动维护时间戳
    protected $autoWriteTimestamp = true;

    // 创建虚拟对象后的操作
    public static function onAfterInsert($dummy)
    {
        // 创建虚拟任务分值
        DummyScore::create(['dummy_id' => $dummy->id, 'total_score' => 100]);
        // 缓存
        DummyCache::setUserDummyById($dummy->user_id, $dummy);
    }

    public static function onAfterUpdate($dummy)
    {
        // 更新后同步更新缓存
        DummyCache::setUserDummyById($dummy->user_id, $dummy);
    }

    /**
     * @todo 将虚拟对象标签信息数组转为json字符串保存
     * @param $value
     * @return string
     * @throws \GuzzleHttp\Exception\InvalidArgumentException
     */
    public function setLabelsAttr($value)
    {
        return json_encode($value);
    }

    /**
     * @todo 取出虚拟对象标签labels时将json字符串转为数组
     * @param $value
     * @return mixed
     * @throws \GuzzleHttp\Exception\InvalidArgumentException
     */
    public function getLabelsAttr($value)
    {
        return json_decode($value);
    }

    // 该纪念日的所属用户
    public function user()
    {
        $this->belongsTo(User::class);
    }

    // 虚拟人物的分值
    public function score()
    {
        return $this->hasOne(DummyScore::class, 'dummy_id', 'id');
    }

    // 虚拟人物恋爱随笔
    public function jottings()
    {
        return $this->hasMany(DummyJotting::class, 'dummy_id', 'id');
    }

}
